<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="12" style="height:100%">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>角色配置</span>
            <el-button style="float: right;" icon="el-icon-lx-add" type="button" v-has="'menu_add'" @click="() => handleAdd()">新增</el-button>
          </div>
          <div class="table">
            <div class="handle-box">
              <el-input v-model="query.name" placeholder="角色名称" class="handle-input mr10"></el-input>
              <el-button type="primary" icon="search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table :data="list.data" border class="table" ref="multipleTable">
              <el-table-column type="selection" width="55" align="center"></el-table-column>
              <el-table-column prop="roleName" label="角色名" v-if="this.$permissions.checkColumn('role_roleName')">
              </el-table-column>
              <el-table-column label="操作" align="center" v-if="this.$permissions.checkColumn('role_opera')">
                <template slot-scope="scope">
                  <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)" v-has="'role_edit'">编辑</el-button>
                  <el-button type="text" icon="el-icon-edit" @click="setCheckedKeys(scope.row)" v-has="'role_menu'">权限配置</el-button>
                  <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.row)" v-has="'role_del'">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination">
              <el-pagination background @size-change="handlePageSize" @current-change="handlePageIndex" :current-page="query.pageIndex" :page-sizes="[10, 20, 30, 50, 150, 200]" layout="total, sizes, prev, pager, next, jumper" :page-size="query.pageSize" :total="list.total">
              </el-pagination>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header" class="clearfix">
            <span>权限配置</span>
            <el-button style="float: right;" icon="el-icon-lx-add"  type="button" v-has="'role_menusave'" @click="handleSaveMenuButton">保存</el-button>
          </div>          
          <div class="custom-tree-container" style="height:100%;overflow-y:auto">
            <div class="block">
              <el-tree :data="data" show-checkbox node-key="keyStr" ref="tree"  :expand-on-click-node="false">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span class="custom-tree-node-data">{{ data.menuName }}</span>
                </span>
              </el-tree>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="form.show" width="30%">
            <el-form ref="form" :model="form.model" :rules="form.rules" label-width="80px">
                <el-form-item label="角色名" prop="roleName">
                    <el-input v-model="form.model.roleName"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                  <el-radio-group v-model="form.model.mark">
                    <el-radio :label="1">启用</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="form.show = false">取 消</el-button>
                <el-button type="primary" @click="handleSaveEdit">确 定</el-button>
            </span>
        </el-dialog>
  </div>
</template>

<script>
import {
  getPage,
  save,
  remove,
  getAllMenuAndButton
} from "@/api/system/role";
export default {
  data() {
    return {
      data: [],
      query: {
        name: "",
        phone: "",
        pageIndex: 1,
        pageSize: 10
      },
      list: {
        loading: false,
        total: 0,
        data: []
      },
      form: {
        show: false,
        model: {
          roleId: 0,
          roleName: "",
          mark: 1,
          roleMenu: "",
          roleButton: ""
        },
        rules:{
          roleName: [
            { required: true, message: '请输入角色名', trigger: 'blur' }
          ],
        }
      }
    };
  },
  created() {
    this.getListData();
    this.getAllMenu();
  },
  methods: {
    getAllMenu() {
      getAllMenuAndButton().then(res => {
        this.data = JSON.parse(JSON.stringify(res.data));
      });
    },
    getListData() {
      getPage(this.query).then(res => {
        this.list.data = res.data.items;
        this.list.total = res.data.totalCount;
      });
    },
    handlePageSize(pageSize) {
      this.query.pageSize = pageSize;
      this.getListData();
    },
    handlePageIndex(pageIndex) {
      this.query.pageIndex = pageIndex;
      this.getListData();
    },
    handleSearch() {
      this.query.pageIndex = 1;
      this.query.pageSize = 10;
      this.getListData();
    },
    handleAdd(row) {
      this.form.model = {
        roleId: 0,
        roleName: "",
        mark: 1,
        roleMenu: "",
        roleButton: "",
        roleColumn: ""
      };
      this.form.show = true;
    },
    handleEdit(row) {
      this.form.model = Object.assign({}, row);
      this.form.show = true;
    },
    handleSaveEdit() {
      this.$refs["form"].validate((valid) => {
        if(valid){
          save(this.form.model).then(res => {
            if (res.status === 200) {
              this.form.show = false;
              this.$message({
                message: "操作成功",
                type: "success"
              });
              this.getListData();
            }
          });
        }else{
          this.$message({ message: "输入错误", type: 'error' })
          return false;
        }
      })
    },
    handleDelete(data) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          remove({ Id: data.roleId }).then(res => {
            if (res.status === 200) {
              this.form.show = false;
              this.$message({
                message: "删除成功",
                type: "success"
              });
              this.getListData();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    setCheckedKeys(row) {
      this.form.model = row;
      let roleMenu = row.roleMenu.split(",");
      let rolebutton = row.roleButton.split(",");
      let rolecolumn = row.roleColumn.split(",");
      let allRole = [];
      roleMenu.map((item, index) => {
        allRole.push("menu_" + item);
      });
      rolebutton.map((item, index) => {
        allRole.push("button_" + item);
      });
      rolecolumn.map((item, index) => {
        allRole.push("column_" + item);
      });
      console.log(allRole)
      this.$refs.tree.setCheckedKeys(allRole);
      let halfChecked = this.$refs.tree.getHalfCheckedKeys();
      let checked = this.$refs.tree.getCheckedKeys();
      checked.map((item, index) => {
        if (allRole.indexOf(item) === -1) {
          this.$refs.tree.setChecked(item, false);
        }
      });
      halfChecked.map((item, index) => {
        if (allRole.indexOf(item) === -1) {
          this.$refs.tree.setChecked(item, false);
        }
      });
    },
    handleSaveMenuButton() {
      if (this.form.model.roleId == 0) {
        this.$message({
          message: "请选择要配置的角色",
          type: "warning"
        });
        return;
      }
      let halfChecked = this.$refs.tree.getHalfCheckedKeys();
      let checked = this.$refs.tree.getCheckedKeys();
      let roleMenu = [];
      let roleButton = [];
      let roleColumn = [];
      halfChecked.map((item, index) => {
        if (item.indexOf("menu_") !== -1) {
          roleMenu.push(item.replace("menu_", ""));
        }
        if (item.indexOf("button_") !== -1) {
          roleButton.push(item.replace("button_", ""));
        }
        if (item.indexOf("column_") !== -1) {
          roleColumn.push(item.replace("column_", ""));
        }
      });
      checked.map((item, index) => {
        if (item.indexOf("menu_") !== -1) {
          roleMenu.push(item.replace("menu_", ""));
        }
        if (item.indexOf("button_") !== -1) {
          roleButton.push(item.replace("button_", ""));
        }
        if (item.indexOf("column_") !== -1) {
          roleColumn.push(item.replace("column_", ""));
        }
      });
      this.form.model.roleMenu = roleMenu.join(",");
      this.form.model.roleButton = roleButton.join(",");
      this.form.model.roleColumn = roleColumn.join(",");
      save(this.form.model).then(res => {
        if (res.status === 200) {
          this.form.show = false;
          this.$message({
            message: "操作成功",
            type: "success"
          });
          this.getListData();
        }
      });
    }
  }
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
</style>
